package com.fiximusic.contorller;

import java.io.File;
import java.io.IOException;
import java.util.Date;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

import org.apache.commons.io.FileUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.commons.CommonsMultipartFile;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import com.fiximusic.common.Constant;
import com.fiximusic.common.Util;
import com.fiximusic.entities.Singer;
import com.fiximusic.entities.Song;
import com.fiximusic.service.HomeService;

@Controller
public class HomeContorller {

	private static final String BASE_PATH = "home/";

	@Resource
	private HomeService hs;

	/**
	 * 首页
	 */
	@RequestMapping("/home/index")
	public String index(@RequestParam(value="page", required=false, defaultValue="1") int currPage,
			ModelMap model) {
		model.addAttribute("songs", hs.getSongsPre10());
		model.addAttribute("singers", hs.getSingersPre10());
		return new StringBuffer( 64).append( BASE_PATH).append( "index").toString();
	}

	/**
	 * 搜索结果
	 * @return
	 */
	@RequestMapping("/home/search")
	public String search(@RequestParam(value="keys", required=false, defaultValue="") String keys,
			Model model) {
		Song s = new Song();
		s.setSongName( keys);
		s.setSongType( keys);
		s.setSongState( Constant.STATE_NORM);
		model.addAttribute("songs", hs.getSearchRs( s));
		return new StringBuffer( 64).append( BASE_PATH).append( "search_result").toString();
	}

	/**
	 * 点击音乐播放
	 */
	@RequestMapping("/home/play")
	public String play(@RequestParam(value="id", required=false, defaultValue="") String id,
			Model model) {
		Song s = hs.getSongByPri( id);
		if( !s.getSongState().equals( Constant.STATE_NORM)) {
			//被删除
		}
		model.addAttribute("song", s);
		return new StringBuffer( 64).append( BASE_PATH).append( "playmusic").toString();
	}

	@Value("${system.fileupload.path}")
	private String upload;

	/**
	 * 上传页面
	 */
	@RequestMapping("/home/uploadHtml")
	public String uploadHtml( Model model, 
			@RequestParam(value="reStr", required=false, defaultValue="") String reStr) {
		model.addAttribute("reStr", reStr);
		return new StringBuffer( 64).append( BASE_PATH).append( "upload").toString();
	}
	/**
	 * 上传音乐
	 * @param name
	 * @param mFile
	 * @return
	 * @throws IOException 
	 */
	@RequestMapping("/home/upload")
	public String upload(@RequestParam(value="siname", required=false, defaultValue="") String siname,
			@RequestParam(value="sotype", required=false, defaultValue="流行") String sotype,
			RedirectAttributes model,
			HttpServletRequest request,
			@RequestParam("song") CommonsMultipartFile  songFile,
			@RequestParam("ly") CommonsMultipartFile  lyFile ) throws IOException { //请求参数一定要与form中的参数名对应
		String realPath = request.getSession().getServletContext().getRealPath( upload);  
		String reStr = "";
		if( songFile.isEmpty()){  
			reStr = "没有上传音乐文件！";
		}else if( Util.isEmpty( siname)){  
			reStr = "没有填写歌手信息";
		} else {
			Singer singer = new Singer();
			singer.setSingerState( Constant.STATE_NORM);
			singer.setSingerName( siname);
			if( (singer = hs.getSinger( singer)) == null) {
				singer = new Singer();
				singer.setSingerState( Constant.STATE_NORM);
				singer.setSingerName( siname);
				singer.setSingerId( Util.generateUUID());
				hs.insertSinger( singer);
			}
			Song song = new Song();
			song.setSingerId( singer.getSingerId());
			song.setSongId( Util.generateUUID());
			song.setSongLocation( new StringBuffer( 512).append( upload).append( "/").append( singer.getSingerName()).append( "/").append( Util.generateUUID()).append( songFile.getOriginalFilename().substring( songFile.getOriginalFilename().lastIndexOf("."))).toString());
			song.setSongName( songFile.getOriginalFilename().substring( 0, songFile.getOriginalFilename().lastIndexOf(".")));
			song.setSongState( Constant.STATE_NORM);
			song.setSongType( sotype);
			song.setSongIssuedate( new Date());;
			//这里不必处理IO流关闭的问题，因为FileUtils.copyInputStreamToFile()方法内部会自动把用到的IO流关掉，我是看它的源码才知道的  
			FileUtils.copyInputStreamToFile( songFile.getInputStream(), new File( new StringBuffer( 512).append( realPath).append("/").append( song.getSongLocation().substring( song.getSongLocation().indexOf( "/"))).toString()));  
			if( !lyFile.isEmpty()) {
				song.setSongLyric( new StringBuffer( 512).append( upload).append( "/").append( singer.getSingerName()).append( "/").append( Util.generateUUID()).append( lyFile.getOriginalFilename().substring(lyFile.getOriginalFilename().lastIndexOf("."))).toString());
				FileUtils.copyInputStreamToFile( lyFile.getInputStream(), new File( new StringBuffer( 512).append( realPath).append("/").append( song.getSongLyric().substring( song.getSongLyric().indexOf( "/"))).toString()));  
				System.out.println("url:" + song.getSongLocation());
			}
			hs.insertSong( song);
			reStr = "上传成功";
		}  
		model.addAttribute("reStr", reStr);
		return new StringBuffer( 128).append( "redirect:/home/uploadHtml.html").toString();
	}
}
